import { ref } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios'
import { ElMessage, ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
import { userId, addUserInfo } from './user'
import { reverseList } from './chatRecording'
import { friendId } from './friend'
import { middlePage, rightPage } from './page'
import { friendSort } from './getFriend'


function friendApply(data) {
    if (data.status === '待处理') {
        ElNotification({
            title: '好友申请',
            message: data.user1Name + '申请添加你为好友',
            type: 'info',
        })
    }
    else if (data.status === '已同意') {
        ElNotification({
            title: 'Success',
            message: data.user2Name + '同意了你的好友申请',
            type: 'success',
        })
    }
    else if (data.status === '已拒绝') {
        ElNotification({
            title: 'Refuse',
            message: data.user2Name + '拒绝了你的好友申请',
            type: 'error',
        })
    }
}

function prompt(data) {
    // console.log(data)
    if(data.sendUserId !== friendId.value){
        ElNotification({
            title: '消息通知',
            message: data.sendUserName + '给你发送了一条消息',
            type: 'info',
        })
    }
}

export const useLoginStore = defineStore('login', () => {

    const router = useRouter()
    const phone = ref('')
    const password = ref('')
    const code = ref(0)
    const user2 = ref()

    //websocket---实现实时通信
    function connection() {
        const sockets = ref({})
        sockets.socket = new WebSocket('wss://47.120.69.214:8787/websocket/' + userId.value);
        //连接webscoket,实现实时监听信息的发送
        sockets.socket.onopen = function () {
            console.log('Connected to server' + userId.value); // 连接成功
        }
        //监听websocket消息,当连接的用户发送消息时，服务器会将消息推送给其他用户，实现实时通信
        //当消息、好友申请、好友删除等事件发生时，服务器会推送消息给客户端，客户端接收到消息后，进行相应的处理
        sockets.socket.onmessage = function (e) {
            console.log(e.data)
            let data = JSON.parse(e.data)
            if (data.type === 'message') {
                //webscoket监听消息
                if (data.message.sendUserId !== userId.value && (userId.value !== friendId.value || data.message.targetType === 'group')) {
                    if(data.message.targetType === 'user' || data.message.targetType === 'group' 
                        && data.message.receiveUserId === friendId.value){
                        reverseList.value.push(data.message)
                        // console.log(data.message)
                        if(data.message.targetType === 'user' && data.message.receiveUserId !== friendId.value){
                        prompt(data.message)
                        }
                    }
                    // console.log(data.message)
                    friendSort(data.message.sendUserId, data.message.targetType, data.message.receiveUserId)
                    // console.log(reverseList.value)
                }
            }
            else if (data.type === 'friend_apply') {
                //webscoket监听好友申请
                friendApply(data.friendApply)
            }
            else if(data.type === 'friend_delete'){
                //webscoket监听好友删除
                ElNotification({
                    title: 'Delete',
                    message: data.friendDelete.userName + '删除了你',
                    type: 'error',
                })
            }
            // else if(data.type === 'friend_delete'){
            //     ElNotification({
            //         title: 'Delete',
            //         message: data.user2Name + '删除了你',
            //         type: 'error',
            //     })
            // }
        }
    }

    function login() {
        axios({
            method: 'post',
            url: 'https://47.120.69.214:8787/user/login',
            data: {
                "phone": phone.value,
                "password": password.value
            },
            headers: {
                'Content-Type': 'application/json'
            }
        }).then((response) => {
            response.data
            sessionStorage.setItem('user', JSON.stringify(response.data))
            user2.value = JSON.parse(sessionStorage.getItem('user'))
            if (user2.value !== null) {
                addUserInfo()
                router.push('/chatInterface')
            }
            if (response.status === 200) return Promise.resolve(ElMessage.success('登录成功'))
        })
            .catch((error) => {
                console.log(error)
                if (error.response.status === 611) return Promise.reject(ElMessage.error('该用户不存在'))
                else if (error.response.status === 613) return Promise.reject(ElMessage.error('密码错误'))
            }
            )
    }

    return {
        phone,
        password,
        login,
        code,
        connection
    }
})